<?php

/**
 * Erra_Serialization_SerializerJson - Serializing class for fields, using JSON format for speed and portability
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_Serialization_SerializerJson {
    /**
     * USerializer::unserializeRaw() - Unserializes raw data
     *
     * @param mixed $datas
     * @return
     */
    public static function unserializeRaw($datas)
    {
        // Disable e_notice display in firebug

        FB::setEnabled(false);
        $result = is_array($datas) ? $datas : (is_numeric($datas) ?  $datas : json_decode($datas, true));
        FB::setEnabled(true);

        return ($result === null) ? $datas : $result;
    }

    /**
     * USerializer::serializeRaw() - Serializes data in database
     *
     * @param mixed $datas
     * @return
     */
    public static function serializeRaw($datas)
    {
        if (is_string($datas))
            return $datas;
        return json_encode($datas);
    }

    /**
     * USerializer::serializeField() - Serializes field rawData
     *
     * @param mixed $field
     * @param mixed $lang
     * @return
     */
    public static function serializeField($field, $lang = null)
    {
        $langs = array_keys(Erra_Core_Locale::getAvailableLangs());
        $associativeData = Erra_Fields_Base_Field::getRawDataAssociative($field, $lang);
        if (is_array($associativeData))
            return self::serializeRaw($associativeData);
        else
            return $associativeData;
        
    }

    /**
     * USerializer::unserializeField() - Unserializes a field from serialized string
     *
     * @param mixed $field
     * @param mixed $serializedString
     * @return
     */
    public static function unserializeField(&$field, $serializedString)
    {
        if (is_array($serializedString)) {
            $rawData = $serializedString;
        } else {
            $rawData = self::unserializeRaw($serializedString);
        }
        $field->setRawData(object_to_array($rawData));
    }
    
}